package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthServiceConstant;
import com.atguigu.common.vo.MemberVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName LoginUserInterceptor
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/7/18
 * @Version 1.0
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<MemberVo> threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        //如果请求uri匹配上了/order/order/status/**,则无需登录就放行
        boolean match = antPathMatcher.match("/order/order/status/**", requestURI);
        boolean match2 = antPathMatcher.match("/payed/notify", requestURI);
        if(match || match2){
            return true;
        }

        MemberVo attribute = (MemberVo) request.getSession().getAttribute(AuthServiceConstant.SESSION_USER_NAME);
        if(attribute !=null){
            threadLocal.set(attribute);
            return true;
        }else {
            request.getSession().setAttribute("msg","请先进行登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
